<?php

namespace app\models;

use Yii;
use app\models\BlxbgameUser;
/**
 * This is the model class for table "blxbgame_morning".
 *
 * @property integer $id
 * @property integer $userid
 * @property string $time
 * @property string $msectime
 * @property integer $signdays
 * @property integer $totalscore
 */
class BlxbgameMorning extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'blxbgame_morning';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
             [['userid', 'time'], 'required'],
             [['signdays', 'totalscore'], 'integer'],
             [['time'], 'safe'],
             [['msectime'], 'string', 'max' => 10],
             [['userid'], 'unique'],
            [['userid', 'time'], 'unique', 'targetAttribute' => ['userid', 'time'], 'message' => 'The combination of 用户序号 and 签到时间 has already been taken.'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '起床表序号',
            'userid' => '用户序号',
            'time' => '签到时间',
            'msectime' => '签到精确时间',
            'signdays' => '连续签到天数',
            'totalscore' => '总分',
        ];
    }

    public static function data_by_id($userid){
        $data = BlxbgameMorning::find()->where('userid = :userid',[':userid'=>$userid] )->asArray()->one();

        //echo $data->createCommand()->getRawSql();
        return $data;
    }
    public static function yesterdayIsSignUp($userid){
        date_default_timezone_set('Asia/Shanghai');
        $today = date ( 'Y-m-d' );
        $yesterday = date("Y-m-d",time()-24*60*60);
        $data = BlxbgameMorning::find()->where('time >= :time1 and time < :time2 and userid = :userid',[':userid'=>$userid,':time1'=>$yesterday,':time2'=>$today])->asArray()->one();
        return $data;
    }
    public static function saveData($data){
        $model = new BlxbgameMorning();
        $model = $model->find()->where('userid = :userid',[':userid'=>$data['userid']] );
        $res =  $model->one();

        if($res == NULL) {
            //数据不存在的时候
            $model_save = new BlxbgameMorning();
            if ($model_save->load($data,'') && $model_save->save()) {
                
                return true;
            }
            $log_content = "修改morning表(起床总表)失败，无法修改起床时间，连续签到时间|用户信息：".var_export($data, true)."\n";
            //$log_content.= $model->createCommand()->getRawSql()."\n";
            Yii::warning($log_content);
            return false;
        }
        else{
            if ($res->load($data,'') && $res->save()) {
                return true;
            }
            $log_content = "修改morning表(起床总表)失败，无法修改起床时间，连续签到时间|用户信息：".var_export($data, true)."\n";
            $log_content.= $model->createCommand()->getRawSql()."\n";
            Yii::warning($log_content);
            return false;
        }
    }

    public static function getMorningRank($time,$msectime){
        date_default_timezone_set('Asia/Shanghai');
        $today = date ( 'Y-m-d' );
       $count = BlxbgameMorning::find()->where('(time >= :today and time < :time) OR (time = :time  AND msectime < :msectime) ',[':today'=>$today,':time'=>$time,':msectime'=>$msectime])->count();
       return $count+1;
    }

    public static function getTotalScoreRank($totalscore,$msectime){
        $count = BlxbgameMorning::find()->where('totalscore > :totalscore OR (totalscore = :totalscore AND msectime < :msectime) ',[':totalscore'=>$totalscore,':msectime'=>$msectime])->count();
        return $count+1;
    }

    //起床排行前10名
    public static function TopTenbydatatime(){
        date_default_timezone_set('Asia/Shanghai');
        $today = date ( 'Y-m-d' );
        $data  = BlxbgameMorning::find()->where('time >= :time',[':time'=>$today])->orderBy('time asc , msectime asc')->limit(30)->asArray()->all();
        $i=0;
         $j=1;
        foreach ($data  as $value){
            $res =BlxbgameUser::data_by_id($value['userid']);
           // var_dump($res['nickname']);
            $time = explode(' ',$value['time']);
            preg_match('/[0-9][0-9]:[0-9][0-9]/', $time['1'],$matches);
            $time = $matches['0'];
            $arr[$i]=array(
                'rank'=> $j,
                'nickname'=>$res['nickname'],
                'time'=> $time,
            );
            $i++;
            $j++;
        }
        
        return $arr;
    }

    public static function LastTenbydatatime(){
        date_default_timezone_set('Asia/Shanghai');
        $today = date ( 'Y-m-d' );
        $data  = BlxbgameMorning::find()->where('time >= :time',[':time'=>$today])->orderBy('id desc')->orderBy('msectime DESC')->limit(3)->asArray()->all();
        $i=0;
        $j=10;
        foreach ($data  as $value){
            $res =BlxbgameUser::data_by_id($value['userid']);

             $time = explode(' ',$value['time']);
            preg_match('/[0-9][0-9]:[0-9][0-9]/', $time['1'],$matches);
            $time = $matches['0'];
            $arr[$i]=array(
                'rank'=> $j,
                'nickname'=>$res['nickname'],
                'time'=> $time,
            );
            $i++;
            $j--;
        }
        return $arr;
    }

    public static function TopTenbyScore(){
        $data  = BlxbgameMorning::find()->orderBy('totalscore desc,msectime DESC')->limit(30)->asArray()->all();
        $i=0;
        $j=1;
        foreach ($data  as $value){
            $res =BlxbgameUser::data_by_id($value['userid']);

            
            $arr[$i]=array(
                'rank'=> $j,
                'nickname'=>$res['nickname'],
                'totalscore'=> $value['totalscore'],
            );
            $i++;
            $j++;
        }
        return $arr;
    }

    public static function update_TotalScore($morningResult){

        $data = BlxbgameMorning::find()->where('userid = :userid',[':userid'=>$morningResult['userid']])->one();
    
        
        if($data){
            //var_dump(123);
                $data->totalscore=$morningResult['totalscore'];
                if ($data->save()) {
                   return true;
                } 
                else{
                   return false;
                }
        }else{
            return false;
        }
    }
}
